#include "serveroperationthread.h"
#include <QDebug>

ServerOperationThread::ServerOperationThread() {
}

void ServerOperationThread::run() {
    QByteArray bytes;
    bytes.resize(infoHead->getFileSize());
    dataStream->readRawData(bytes.data(), bytes.size());
    switch (static_cast<Operation::Opcode>(infoHead->getOperation())) {
        case Operation::SignUpAvator:
            signUpAvator(bytes);
            break;
        case Operation::SendImgMsg:
            sendImgMsg(bytes);
            break;
        case Operation::SendVoiceMsg:
            sendVoiceMsg(bytes);
            break;
        case Operation::SendFileMsg:
            sendFileMsg(bytes);
            break;
        case Operation::OfflineSendTextMsg:
            offlineSendTextMsg(bytes);
            break;
        case Operation::OfflineSendImgMsg:
            offlineSendImgMsg(bytes);
            break;
        case Operation::OfflineSendVoiceMsg:
            offlineSendVoiceMsg(bytes);
            break;
        default:
            return defaultReturn();
    }
}

void ServerOperationThread::sendFileMsg(QByteArray bytes) {
    QSqlTableModel *userIpModel;
    userIpModel = new QSqlTableModel();
    userIpModel->setTable("user_ip");
    userIpModel->setFilter(QObject::tr("user_id = %1").arg(infoHead->getDes()));
    userIpModel->select();

    if (userIpModel->rowCount() != 1) {
        InfoHead *reInfoHead = new InfoHead(0, 1, Operation::ReSendFileMsg, Operation::Fail,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          QString(""));
        TRANS->writeUdp(reInfoHead, QByteArray(), ip, port);
        return;
    }

    QString reIp = userIpModel->record(0).value("ip").toString();
    int fileSize = bytes.size();
    qint64 timestamp = QDateTime::currentDateTime().toSecsSinceEpoch();
    QString fileName = infoHead->getFileName();
    QString reFileName = QObject::tr("%1-%2-%3").arg(QString::number(infoHead->getSrc()), QString::number(timestamp), fileName);
    InfoHead *reInfoHead = new InfoHead(fileSize, 1, Operation::ReSendFileMsg, Operation::Success,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          reFileName);
    TRANS->writeTcp(reInfoHead, bytes, QHostAddress(reIp), SYSCONF.tcpPort);
}

void ServerOperationThread::sendVoiceMsg(QByteArray bytes){
    QSqlTableModel *userIpModel;
    userIpModel = new QSqlTableModel();
    userIpModel->setTable("user_ip");
    userIpModel->setFilter(QObject::tr("user_id = %1").arg(infoHead->getDes()));
    userIpModel->select();

    if (userIpModel->rowCount() != 1) {
        InfoHead *reInfoHead = new InfoHead(0, 1, Operation::ReSendImgMsg, Operation::Fail,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          QString(""));
        TRANS->writeUdp(reInfoHead, QByteArray(), ip, port);
        return;
    }

    QString reIp = userIpModel->record(0).value("ip").toString();
    int fileSize = bytes.size();
    qint64 timestamp = QDateTime::currentDateTime().toSecsSinceEpoch();
    QString fileName = infoHead->getFileName();
    QString reFileName = QObject::tr("%1-%2-%3").arg(QString::number(infoHead->getSrc()), QString::number(timestamp), fileName);
    InfoHead *reInfoHead = new InfoHead(fileSize, 1, Operation::ReSendVoiceMsg, Operation::Success,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          reFileName);
    TRANS->writeTcp(reInfoHead, bytes, QHostAddress(reIp), SYSCONF.tcpPort);

}

void ServerOperationThread::sendImgMsg(QByteArray bytes) {
    QSqlTableModel *userIpModel;
    userIpModel = new QSqlTableModel();
    userIpModel->setTable("user_ip");
    userIpModel->setFilter(QObject::tr("user_id = %1").arg(infoHead->getDes()));
    userIpModel->select();


    if (userIpModel->rowCount() != 1) {
        InfoHead *reInfoHead = new InfoHead(0, 1, Operation::ReSendImgMsg, Operation::Fail,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          QString(""));
        TRANS->writeUdp(reInfoHead, QByteArray(), ip, port);
        return;
    }

    QString reIp = userIpModel->record(0).value("ip").toString();
    int fileSize = bytes.size();
    qint64 timestamp = QDateTime::currentDateTime().toSecsSinceEpoch();
    QString fileName = infoHead->getFileName();
    QString reFileName = QObject::tr("%1-%2-%3").arg(QString::number(infoHead->getSrc()), QString::number(timestamp), fileName);
    InfoHead *reInfoHead = new InfoHead(fileSize, 1, Operation::ReSendImgMsg, Operation::Success,
                                          infoHead->getSrc(), infoHead->getDes(),
                                          reFileName);
    TRANS->writeTcp(reInfoHead, bytes, QHostAddress(reIp), SYSCONF.tcpPort);
}

void ServerOperationThread::offlineSendTextMsg(QByteArray bytes) {
    qDebug() << "\033[35m =] offlineSendTextMsg \033[0m";
    QFile file(SYSCONF.localDataPath + "solooffline/" + QString::number(infoHead->getDes()) + ".json");
    if (!file.exists()) {
        qDebug() << "\033[35m =] !file.exists() \033[0m";
        file.open(QIODevice::WriteOnly);
    } else {
        qDebug() << "\033[35m =] file.exists() \033[0m";
        file.open(QIODevice::ReadOnly);
    }
}

void ServerOperationThread::offlineSendImgMsg(QByteArray bytes) {

}

void ServerOperationThread::offlineSendVoiceMsg(QByteArray bytes) {

}

void ServerOperationThread::setInfoHead(InfoHead *infoHead) {
    this->infoHead = infoHead;
}

void ServerOperationThread::setDataStream(QDataStream *dataStream) {
    this->dataStream = dataStream;
}

void ServerOperationThread::signUpAvator(QByteArray bytes) {
    QFile file(SYSCONF.localDataPath + "soloavator/" + QString::number(getCurrentUserId()) + ".png");
    file.open(QFile::WriteOnly);
    file.write(bytes);
    file.close();

    QJsonDocument *doc = new QJsonDocument();
    QJsonObject obj;
    obj.insert("path",
               SYSCONF.localDataPath + "soloavator/" + QString::number(getCurrentUserId()) + ".png");
    doc->setObject(obj);

    TRANS->writeUdp(new InfoHead(doc->toJson().size(), 0,
                                 Operation::ReSignUpAvator, Operation::Success,
                                 getCurrentUserId(), 0, QString("")),
                    doc->toJson(),
                    ip, port);
}

qint32 ServerOperationThread::getCurrentUserId(){
    QSqlTableModel *userInfoModel;
    userInfoModel = new QSqlTableModel();
    userInfoModel->setTable("user_info");
    return userInfoModel->rowCount();
}
void ServerOperationThread::defaultReturn() {
    qDebug() << "\033[32mServerOperationThread::exec switch in default case \033[0m";
}

void ServerOperationThread::setPort(const quint16 &port)
{
    this->port = port;
}

void ServerOperationThread::setIp(const QHostAddress &ip)
{
    this->ip = ip;
}
